<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>WebChat</title>
    <style>
        /* 添加基本样式 */
        body { font-family: Arial, sans-serif; margin: 0; padding: 0; }
        #chat-container { display: flex; height: 100vh; }
        #sidebar { 
            width: 250px; 
            background: #f0f0f0; 
            padding: 10px;
            display: flex;
            flex-direction: column;
        }
        #search-container {
            display: flex;
            margin-bottom: 10px;
        }
        #search-input {
            flex: 1;
            padding: 5px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        #search-button {
            margin-left: 5px;
            padding: 5px 10px;
            background: #007bff;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        #search-results {
            flex: 1;
            overflow-y: auto;
            border-top: 1px solid #ddd;
            margin-top: 10px;
            padding-top: 10px;
        }
        .search-result {
            padding: 5px;
            margin-bottom: 5px;
            border-bottom: 1px solid #eee;
            cursor: pointer;
        }
        .search-result:hover {
            background: #e9e9e9;
        }
        .highlight {
            background-color: yellow;
            font-weight: bold;
        }
        #chat-area { flex: 1; display: flex; flex-direction: column; }
        #messages { flex: 1; overflow-y: auto; padding: 10px; }
        #message-form { 
            display: flex; 
            padding: 10px;
            background: #f5f5f5;
            border-top: 1px solid #ddd;
        }
        #message-input { 
            flex: 1; 
            margin-right: 10px;
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 20px;
            outline: none;
        }
        #message-input:focus {
            border-color: #007bff;
        }
        #send-button {
            background: #007bff;
            color: white;
            border: none;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        #send-button:hover {
            background: #0069d9;
        }
        #upload-button {
            margin-right: 10px;
            background: transparent;
            border: none;
            font-size: 1.2em;
            cursor: pointer;
        }
        #file-input {
            display: none;
        }
        .image-message {
            max-width: 300px;
            max-height: 300px;
            border-radius: 8px;
        }
        .image-preview {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.8);
            display: none;
            justify-content: center;
            align-items: center;
            z-index: 1000;
        }
        .preview-image {
            max-width: 90%;
            max-height: 90%;
        }
        .close-preview {
            position: absolute;
            top: 20px;
            right: 20px;
            color: white;
            font-size: 30px;
            cursor: pointer;
        }
        .typing-indicator {
            font-style: italic;
            color: #666;
            padding: 5px 15px;
        }
        .message-status {
            font-size: 0.8em;
            color: #666;
            text-align: right;
            padding-right: 10px;
        }
        
        .message { 
            margin: 10px;
            padding: 10px;
            border-radius: 8px;
            max-width: 70%;
            word-wrap: break-word;
            position: relative;
        }
        .message-menu {
            display: none;
            position: absolute;
            right: 0;
            top: 0;
            background: white;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.2);
            z-index: 100;
        }
        .message:hover .message-menu {
            display: block;
        }
        .message-menu button {
            display: block;
            width: 100%;
            padding: 5px 10px;
            border: none;
            background: none;
            text-align: left;
            cursor: pointer;
        }
        .message-menu button:hover {
            background: #f5f5f5;
        }
        .recalled-message {
            color: #999;
            font-style: italic;
        }
        .received { 
            background: #e5e5ea;
            align-self: flex-start;
        }
        .sent { 
            background: #007bff;
            color: white;
            align-self: flex-end;
        }
        .unread {
            border-left: 3px solid #ff5722;
        }
        .message-time {
            font-size: 0.8em;
            opacity: 0.7;
            margin-top: 5px;
        }
        .online-user {
            color: #4CAF50;
            font-weight: bold;
        }
        .offline-user {
            color: #9E9E9E;
        }
    </style>
</head>
<body>
    <div id="chat-container">
        <div id="sidebar">
            <div id="search-container">
                <input type="text" id="search-input" placeholder="搜索聊天记录..."/>
                <button id="search-button">搜索</button>
            </div>
            <div id="search-results" style="display:none;"></div>
            <h3>在线用户</h3>
            <ul id="users"></ul>
        </div>
        <div id="chat-area">
        <div id="messages"></div>
        <form id="message-form">
            <button type="button" id="upload-button">📎</button>
            <input type="file" id="file-input" accept="image/*"/>
            <input id="message-input" type="text" placeholder="输入消息..." autocomplete="off"/>
            <button type="submit" id="send-button">
                <svg width="20" height="20" viewBox="0 0 24 24">
                    <path fill="currentColor" d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"/>
                </svg>
            </button>
        </form>
            <div id="typing-indicator" class="typing-indicator" style="display:none"></div>
        </div>
    </div>
	<th:block th:insert="~{include :: footer}" />
	<script src="/js/sockjs/sockjs.min.js"></script>
	<script src="/js/sockjs/stomp.min.js"></script>

    <script>
        // WebSocket连接和消息处理逻辑
        const socket = new SockJS('/ws');
        const stompClient = Stomp.over(socket);
        
        stompClient.connect({}, function(frame) {
            console.log('Connected: ' + frame);
            
            // 加载历史消息
            fetch('/api/messages?page=0&size=50')
                .then(response => response.json())
                .then(data => {
                    data.content.reverse().forEach(msg => showMessage(msg));
                });
            
            stompClient.subscribe('/topic/public', function(message) {
                showMessage(JSON.parse(message.body));
            });
            
            stompClient.subscribe('/topic/read', function(message) {
                const msgId = JSON.parse(message.body);
                const msgElement = document.querySelector(`[data-message-id="${msgId}"]`);
                if (msgElement) {
                    msgElement.classList.remove('unread');
                }
            });
            
            stompClient.subscribe('/topic/typing', function(username) {
                const typingUser = JSON.parse(username);
                if (typingUser !== currentUser) {
                    const indicator = document.getElementById('typing-indicator');
                    indicator.textContent = `${typingUser} 正在输入...`;
                    indicator.style.display = 'block';
                    setTimeout(() => {
                        indicator.style.display = 'none';
                    }, TYPING_TIMEOUT);
                }
            });
            
            stompClient.subscribe('/topic/recall', function(messageId) {
                const msgId = JSON.parse(messageId);
                const msgElement = document.querySelector(`[data-message-id="${msgId}"]`);
                if (msgElement) {
                    msgElement.innerHTML = `
                        <div class="recalled-message">消息已被撤回</div>
                    `;
                }
            });
        });

        function showMessage(message) {
            const messagesDiv = document.getElementById('messages');
            const messageElement = document.createElement('div');
            
            const isCurrentUser = message.from === currentUser;
            const messageClass = isCurrentUser ? 'sent' : 'received';
            const unreadClass = !isCurrentUser && !message.read ? 'unread' : '';
            
            messageElement.className = `message ${messageClass} ${unreadClass}`;
            messageElement.innerHTML = `
                <div><strong>${message.from}</strong></div>
                <div>${message.content}</div>
                <div class="message-time">${formatTime(message.timestamp)}</div>
                <div class="message-menu">
                    <button onclick="recallMessage('${message.id}')">撤回消息</button>
                </div>
            `;
            
            messageElement.dataset.messageId = message.id;
            messageElement.dataset.sender = message.from;
            messageElement.dataset.read = message.read;
            
            messageElement.addEventListener('click', () => {
                if (!isCurrentUser && !message.read) {
                    stompClient.send("/app/chat.read", {}, JSON.stringify(message.id));
                    messageElement.classList.remove('unread');
                }
            });
            
            messagesDiv.appendChild(messageElement);
            messagesDiv.scrollTop = messagesDiv.scrollHeight;
        }

        function formatTime(timestamp) {
            const date = new Date(timestamp);
            return date.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});
        }

        function updateUserStatus(username, isOnline) {
            const userList = document.getElementById('users');
            const userElement = Array.from(userList.children).find(el => el.textContent === username);
            
            if (userElement) {
                userElement.className = isOnline ? 'online-user' : 'offline-user';
            } else if (isOnline) {
                const li = document.createElement('li');
                li.className = 'online-user';
                li.textContent = username;
                userList.appendChild(li);
            }
        }

        let currentUser = '当前用户'; // 实际应用中应从登录用户获取
        let typingTimeout;
        const TYPING_TIMEOUT = 3000; // 3秒无输入认为停止输入
        
        // 输入状态检测
        document.getElementById('message-input').addEventListener('input', () => {
            clearTimeout(typingTimeout);
            stompClient.send("/app/chat.typing", {}, JSON.stringify(currentUser));
            typingTimeout = setTimeout(() => {
                document.getElementById('typing-indicator').style.display = 'none';
            }, TYPING_TIMEOUT);
        });
        


        // 图片上传处理
        document.getElementById('upload-button').addEventListener('click', () => {
            document.getElementById('file-input').click();
        });

        document.getElementById('file-input').addEventListener('change', (e) => {
            const file = e.target.files[0];
            if (file) {
                const reader = new FileReader();
                reader.onload = (event) => {
                    const imgData = event.target.result;
                    
                    // 创建图片预览
                    const preview = document.createElement('div');
                    preview.className = 'image-preview';
                    preview.innerHTML = `
                        <span class="close-preview">×</span>
                        <img class="preview-image" src="${imgData}"/>
                    `;
                    document.body.appendChild(preview);
                    preview.style.display = 'flex';

                    // 点击关闭预览
                    preview.querySelector('.close-preview').addEventListener('click', () => {
                        preview.style.display = 'none';
                    });

                    // 发送图片消息
                    const message = {
                        from: currentUser,
                        content: '[图片]',
                        image: imgData,
                        timestamp: new Date()
                    };
                    stompClient.send("/app/chat.send", {}, JSON.stringify(message));
                };
                reader.readAsDataURL(file);
            }
        });

        // 修改showMessage函数支持图片显示
        function showMessage(message) {
            const messagesDiv = document.getElementById('messages');
            const messageElement = document.createElement('div');
            
            const isCurrentUser = message.from === currentUser;
            const messageClass = isCurrentUser ? 'sent' : 'received';
            const unreadClass = !isCurrentUser && !message.read ? 'unread' : '';
            
            messageElement.className = `message ${messageClass} ${unreadClass}`;
            
            if (message.image) {
                messageElement.innerHTML = `
                    <div><strong>${message.from}</strong></div>
                    <img src="${message.image}" class="image-message" onclick="showImagePreview('${message.image}')"/>
                    <div class="message-time">${formatTime(message.timestamp)}</div>
                `;
            } else {
                messageElement.innerHTML = `
                    <div><strong>${message.from}</strong></div>
                    <div>${message.content}</div>
                    <div class="message-time">${formatTime(message.timestamp)}</div>
                `;
            }
            
            messageElement.dataset.messageId = message.id;
            messageElement.dataset.sender = message.from;
            messageElement.dataset.read = message.read;
            
            messageElement.addEventListener('click', () => {
                if (!isCurrentUser && !message.read) {
                    stompClient.send("/app/chat.read", {}, JSON.stringify(message.id));
                    messageElement.classList.remove('unread');
                }
            });
            
            messagesDiv.appendChild(messageElement);
            messagesDiv.scrollTop = messagesDiv.scrollHeight;
        }

        function showImagePreview(imgData) {
            const preview = document.createElement('div');
            preview.className = 'image-preview';
            preview.innerHTML = `
                <span class="close-preview">×</span>
                <img class="preview-image" src="${imgData}"/>
            `;
            document.body.appendChild(preview);
            preview.style.display = 'flex';

            preview.querySelector('.close-preview').addEventListener('click', () => {
                preview.style.display = 'none';
            });
        }

        function recallMessage(messageId) {
            stompClient.send("/app/chat.recall", {}, JSON.stringify(messageId));
        }

        // 搜索功能
        document.getElementById('search-button').addEventListener('click', searchMessages);
        document.getElementById('search-input').addEventListener('keyup', (e) => {
            if (e.key === 'Enter') searchMessages();
        });

        function searchMessages() {
            const query = document.getElementById('search-input').value.trim();
            if (!query) {
                document.getElementById('search-results').style.display = 'none';
                return;
            }

            fetch(`/api/messages/search?q=${encodeURIComponent(query)}`)
                .then(response => response.json())
                .then(messages => {
                    const resultsDiv = document.getElementById('search-results');
                    resultsDiv.innerHTML = '';
                    resultsDiv.style.display = 'block';

                    if (messages.length === 0) {
                        resultsDiv.innerHTML = '<div>没有找到匹配的消息</div>';
                        return;
                    }

                    messages.forEach(msg => {
                        const resultDiv = document.createElement('div');
                        resultDiv.className = 'search-result';
                        
                        // 高亮匹配内容
                        const content = msg.content.replace(
                            new RegExp(query, 'gi'), 
                            match => `<span class="highlight">${match}</span>`
                        );
                        
                        resultDiv.innerHTML = `
                            <div><strong>${msg.from}</strong></div>
                            <div>${content}</div>
                            <div class="message-time">${formatTime(msg.timestamp)}</div>
                        `;
                        resultDiv.addEventListener('click', () => {
                            scrollToMessage(msg.id);
                        });
                        resultsDiv.appendChild(resultDiv);
                    });
                });
        }

        function scrollToMessage(messageId) {
            const msgElement = document.querySelector(`[data-message-id="${messageId}"]`);
            if (msgElement) {
                msgElement.scrollIntoView({ behavior: 'smooth' });
                msgElement.style.animation = 'highlight 2s';
                setTimeout(() => {
                    msgElement.style.animation = '';
                }, 2000);
            }
        }

        document.getElementById('message-form').addEventListener('submit', function(e) {
            e.preventDefault();
            const input = document.getElementById('message-input');
            const message = {
                from: '当前用户', // 实际应用中应从登录用户获取
                content: input.value,
                timestamp: new Date()
            };
            stompClient.send("/app/chat.send", {}, JSON.stringify(message));
            input.value = '';
        });
    </script>
</body>
</html>